<template>
  <section>
    <!--#region 搜索条-->

    <xt-search @search="handleSearch" v-if="searchFlag" :searchFlag="getOperation('list')">
      <el-select v-model="filters.appId" :placeholder="$t('user.app')" size="small" class="search-box__input" @change="handleSearch">
        <el-option
          v-for="item in appList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
        <el-input v-model="filters.account" :placeholder="$t('user.account')" size="small" class="search-box__input" clearable @keyup.enter.native="handleSearch"></el-input>
        <el-input v-model="filters.name" :placeholder="$t('user.name')" size="small" class="search-box__input" clearable @keyup.enter.native="handleSearch"></el-input>
        <template slot="actions">
          <el-button size="small" class="search-box__button" type="primary" icon="plus" @click="handleAdd" v-if="getOperation('insert')">{{$t('add')}}</el-button>
        </template>
      </xt-search>

    <!--#endregion-->

    <!--#region 页面主要列表-->

    <!--列表-->

    <div class="search-button">
      <el-button class="button" icon="el-icon-search" circle size="small" @click="handleSearchFlag"></el-button>
    </div>
    <el-table :data="userList" highlight-current-row v-loading="loading.listLoading" style="width: 100%;" stripe border>
      <!--<el-table-column type="expand">-->
      <!--<template slot-scope="scope">-->
      <!--<useritem :userId="scope.row.id" :appId="filters.appId"></useritem>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column align="left" header-align="center" type="index" width="56" :label="$t('index')">
        <template slot-scope="scope">
          {{(pageInfo.pageIndex-1)*pageInfo.pageSize+scope.$index+1}}
        </template>
      </el-table-column>
      <!--<el-table-column-->
      <!--prop="appName"-->
      <!--align="center"-->
      <!--label="所属应用">-->
      <!--</el-table-column>-->
      <el-table-column
        prop="name"
        align="center"
        :label="$t('user.name')">
      </el-table-column>
      <el-table-column
        prop="account"
        align="center"
        :label="$t('user.account')">
      </el-table-column>
      <!-- <el-table-column
               prop="groupId"
               align="center"
               label="分组号">
       </el-table-column>-->
      <el-table-column
        prop="phone"
        align="center"
        :label="$t('user.phone')">
      </el-table-column>
      <el-table-column
        prop="mail"
        align="center"
        label="Email">
      </el-table-column>
      <el-table-column
        prop="qq"
        align="center"
        label="QQ">
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('user.password')">
        <template slot-scope="scope">
          **************
          <el-button type="text" size="small" @click="showToken(scope.$index,scope.row)">{{$t('app.show')}}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('operation')" :width="operationWidth('reset-password|update|delete', 75, 150, 250)" v-if="getOperation('reset-password|update|delete')">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleReset(scope.row)" v-if="getOperation('reset-password')">{{$t('user.resetPassword')}}</el-button>
          <el-button size="small" type="warning" @click="handleEdit(scope.row)" v-if="getOperation('update')">{{$t('edit')}}</el-button>
          <el-button type="danger" size="small" @click="deleteData(scope.row)" v-if="getOperation('delete')">{{$t('delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--#endregion-->

    <!--#region 工具条-->

    <!--工具条-->

    <el-row>
      <el-col :span="24" class="toolbar">
        <el-pagination
          style="float:right;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.pageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageInfo.pageSize"
          layout="sizes, prev, pager, next"
          :total="pageInfo.count">
        </el-pagination>
      </el-col>
    </el-row>

    <!--#endregion-->

    <!--#region 新增修改页面-->

    <!--新增界面-->

    <el-dialog width="95%" top="20px" :title="formData.id==0?$t('add'):$t('modify')" :visible.sync="dialog.formDataVisible" :close-on-click-modal="false" :modal-append-to-body="false">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formData">
        <el-form-item :label="$t('user.account')" prop="account">
          <el-input v-model="formData.account" auto-complete="off" :maxlength="50" :placeholder="$t('user.accountMessage')" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user.name')" prop="name">
          <el-input v-model="formData.name" auto-complete="off" :maxlength="50" :placeholder="$t('user.validateName')" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user.role')" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple :placeholder="$t('user.validateRole')" style="width:100%">
            <el-option v-for="item in roleList" :label="item.name" :value="item.id+''" :key="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('user.phone')" prop="phone">
          <el-input v-model="formData.phone" auto-complete="off" :maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="Email" prop="mail">
          <el-input v-model="formData.mail" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="formData.qq" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user.organizeId')" prop="organizeId">
          <vue-tree-select-validate
            v-model="formData.organizeId"
            :multiple="false"
            :options="organizeList"
            :placeholder="$t('user.validateOrganizeId')"
            :noChildrenText="$t('noData')"
            :noOptionsText="$t('noData')" style="line-height: 30px;margin-top: 4px;"
            size="small"
            :updateFlag="formData.id!==0">
          </vue-tree-select-validate>
        </el-form-item>
        <el-form-item :label="$t('user.workLicenseFlag')" prop="workLicenseFlag">
          <el-radio-group v-model="formData.workLicenseFlag" size="small">
            <el-radio-button :label="true">{{$t('yes')}}</el-radio-button>
            <el-radio-button :label="false">{{$t('no')}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCancel">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click.native="submitData" :loading="loading.addLoading">{{$t('submit')}}</el-button>
      </div>
    </el-dialog>

    <!--#endregion-->

  </section>
</template>

<script>

/*#region 导入函数*/
import {CheckExp, GetExitData, ParamsSelect} from "../../utils/utils";
import PagePlugIn from "../../mixins/page-plug-in";
import {AppAPI, UserAPI, RoleAPI, RoleUserAPI, OrganizeAPI} from "../../modules";

/*#endregion*/

export default {
  name: "User",
  methods: {

    /*#region 自定义函数(组件change事件等)*/
    showToken(index, row) {
      this.$message({
        message: row.name + this.$t('user.password') + ":" + row.password,
        showClose: true
      });
    },

    /*#endregion*/

    /*#region 数据提交事件*/

    //提交事件
    submitData() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.formData));
          ParamsSelect.getAddSelectParams(params, this.organizeList, {
            organizeName: "fullName"
          }, {organizeId: "id"});
          if (params.id === 0) {
            this.loading.addLoading = true;
            UserAPI.insertUser(params).then(({data}) => {
              this.loading.addLoading = false;
              if (data.code === 1) {
                params.id = data.data.id;
                RoleUserAPI.updateRoleUser({userId: params.id, roleIds: params.roleIds.join(",")}).then(({res}) => {
                  this.$refs.formData.resetFields();
                  this.getMainList();
                  this.dialog.formDataVisible = false;
                });
              }
            });
        } else {
          this.loading.addLoading = true;
          UserAPI.updateUser(params).then(({data}) => {
            this.loading.addLoading = false;
            if (data.code === 1) {
              RoleUserAPI.updateRoleUser({userId: params.id, roleIds: params.roleIds.join(",")}).then(({res}) => {
                this.$refs.formData.resetFields();
                this.getMainList();
                this.dialog.formDataVisible = false;
              });
            }
          });
          }
        }
      });
    },

    //删除

    deleteData(row) {
      this.$confirm(this.$t('deleteConfirm'), this.$t('tips'),  {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: "warning"
      }).then(() => {
        UserAPI.deleteUser({id: row.id}).then(({data}) => {
          if (data.code === 1) {
            this.getMainList();
          }
        });
      });
    },


    /*#endregion*/

    /*#region 操作函数(handle)*/
    handleReset(row) {
      this.$confirm(this.$t('user.askResetPassword'), this.$t('tips'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: "warning"
      }).then(() => {
        UserAPI.updateUserResetPassword({id: row.id}).then(({res}) => {
          this.$message({
            showClose: true,
            message: this.$t('user.resetSuccess') + res.data.data.password + "】",
            type: "success",
            duration: 100000
          });
        });
      });
    },
    async handleEdit(row) {
      await RoleAPI.listRole({pageIndex: 1, pageSize: 9999, appId: this.filters.appId}).then(({list}) => {
        this.roleList = list;
      });
      await RoleUserAPI.listRoleUser({pageIndex: 1, pageSize: 999999, userId: row.id, appId: this.filters.appId}).then(({list}) => {
        const roleIds = [];
        list.map((roleItem) => {
          roleIds.push(roleItem.roleId + "");
        });
        row.roleIds = roleIds;
        this.$refs.formData && this.$refs.formData.resetFields();
        this.formData = JSON.parse(JSON.stringify(row));
        this.dialog.formDataVisible = true;
      });
      return true;
    },
    handleCancel() {
      this.dialog.formDataVisible = false;
    },
    handleAdd() {
      RoleAPI.listRole({pageIndex: 1, pageSize: 9999, appId: this.filters.appId}).then(({list}) => {
        this.roleList = list;
        this.$refs.formData && this.$refs.formData.resetFields();
        this.formData = {...UserAPI.init(), appId: this.filters.appId, roleIds: [], workLicenseFlag: true};
        this.dialog.formDataVisible = true;
      });
    },

    /*#endregion*/

    /*#region 获取数据*/

    getMainList() {
      const params = {
        ...this.getParams(),
        appFlag: true
      };
      this.loading.listLoading = true;
      UserAPI.listUser(params).then(({data, list}) => {
        this.loading.listLoading = false;
        this.userList = list;
        this.pageInfo.pageIndex = data.data ? data.data.currentPage : 1;
        this.pageInfo.count = data.data ? data.data.count : 0;
      });
    },
    // 组织架构
    getOrganizeList() {
      const params = {
        ...this.getParams()
      };
      this.loading.listLoading = true;
      OrganizeAPI.listOrganizeTree(params).then(({data, list}) => {
        this.loading.listLoading = false;
        this.organizeList = list;
      });
    }

    /*#endregion*/

  },

  /*#region 生命周期函数(created、mount、等)*/

  created() {
    this.getOrganizeList();
    this.loading.listLoading = true;
    AppAPI.listApp({pageIndex: 1, pageSize: 9999}).then(({list}) => {
      this.appList = list;
      if (list.length > 0) {
        this.filters.appId = list[0].id;
      }
      RoleAPI.listRole({pageIndex: 1, pageSize: 9999, appId: this.filters.appId}).then(({list}) => {
        this.roleList = list;
      });
      this.getMainList();
    });
  },

  /*#endregion*/

  /*#region 注册绑定数据*/

  mixins: [PagePlugIn],
  data() {
    const checkPhone = (rule, value, callback) => {
      if (CheckExp.isTel(value)) {
        callback();
      } else {
        return callback(new Error(this.$t('userInfo.correctNumber')));
      }
    };
    const checkQQ = (rule, value, callback) => {
      if (value) {
        if (CheckExp.isQQ(value)) {
          callback();
        } else {
          return callback(new Error(this.$t('userInfo.correctQQ')));
        }
      } else {
        callback();
      }
    };
    const checkUser = (rule, value, callback) => {
      const param = {account: value, appFlag: true}; //, appId: this.filters.appId
      GetExitData(param, UserAPI.listUser).then(({isEmpty, id}) => {
        if ((id === this.formData.id)) {callback();} else {
          if (!isEmpty) {return callback(new Error(this.$t('user.exitsAccount')));} else {callback();}
        }
      });
    };
    return {
      filters: {...UserAPI.init(), appId: null},
      formData: {...UserAPI.init(), workLicenseFlag: true},
      formRules: {
        account: [
          {required: true, message: this.$t('userInfo.validateAccount'), trigger: "change"},
          {min: 2, max: 50, message: this.$t('userInfo.validateLength50'), trigger: "blur"},
          {validator: checkUser, trigger: "blur"}
        ],
        name: [
          {required: true, message: this.$t('userInfo.validateName'), trigger: "blur"},
          {min: 2, max: 50, message: this.$t('userInfo.validateLength50'), trigger: "blur"}
        ],
      //  groupId: [
      //      {required: true, message: '请输入分组号', trigger: 'blur'}
      //  ],
      // phone: [
      //     {minlength: 11, maxlength: 11,required: true, message: '请输入正确的手机号', trigger: 'blur'},
      //     { validator:checkPhone, trigger: 'blur,change' }
      // ],
        mail: [{ required: false, message: "", trigger: "change" },
          { type: "email", message: this.$t('userInfo.correctEmail'), trigger: "blur,change" }],
        qq: [{required: false, message: "", trigger: "blur"}, { validator: checkQQ, trigger: "change" }],
        roleIds: [{required: true, message: this.$t('user.validateRole'), trigger: "change"}]
      },
      dialog: { formDataVisible: false },
      loading: { addLoading: false, listLoading: false },
      userList: [],
      appList: [],
      roleList: [],
      organizeList: []
    };
  }

  /*#endregion */

};
</script>

<style scoped>

</style>
